from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render
import os
from myweb.message import testJson
import json

## 复制上传文件到 tmp目录
def saveUploadFile(request):
    bFile = False
    file = request.FILES.get("file", None)

    if file is None:
        return bFile, ''

    image_path = 'tmp/%s' % file.name  ##以后加随机数，加图片类型校验等
    # 开启一个流
    image_path = os.path.join(os.getcwd(), image_path).replace('\\', '/') ##完整图片路径

    with open(image_path, 'wb+') as f:
        # 分块写入文件;
        for chunk in file.chunks():
            f.write(chunk)

    bFile = True
    return bFile, image_path

def getDefaultContext():
    context = {
        'statusText': '数据出错，请重新上传！',
        'statusCode': '404',
        'stat': {'health': 0, 'oneleaf': 0, 'partial': 0, 'seeds': 0},
        'boxes': [],
        'img': '',
        'fileImageWebPath': 'img/icon_48.png',
        'fileName' : 'icon_48.png',
    }
    return context
# 2023-12-22 最新批量图片处理结果
def getDefaultContext2():
    context = {
        'statusText': '有图片文件出错，请重新上传！',
        'statusCode': '400',
        'result' : []
        # [{
        #     'stat': {'health': 0, 'oneleaf': 0, 'partial': 0, 'seeds': 0},
        #     'boxes': [],
        #     'img': '',
        #     'fileImageWebPath': 'img/icon_48.png'
        # }]
    }
    return context
## 图片上传的保存路径
def getSaveImagePath(fileName):
    image_path = 'tmp/%s' % fileName  ##以后加随机数，加图片类型校验等
    # 开启一个流
    image_path = os.path.join(os.getcwd(), image_path).replace('\\', '/')  ##完整图片路径
    return image_path

## 返回JSON数据, 测试用
def returnJson(stat, imgcv, detects, fileSaveDrawBox, fileImageWebPath, isImg =False):
    print(stat[0])

    if isImg == True:
        import base64
        with open(fileSaveDrawBox, 'rb') as f:
            data = f.read()
        imgstr = base64.b64encode(data).decode('utf-8')
    else:
        imgstr = ''


    data = {
        'statusText': '图像检测成功！',
        'statusCode': '200',
        'health': stat[0],
        'oneleaf': stat[1],
        'partial': stat[2],
        'seeds': stat[3],
        'boxes': detects.tolist(),
        'img': imgstr,
        'fileImageWebPath': fileImageWebPath,
        'fileName' : fileImageWebPath
    }
    return json.dumps(data)

## 根据YOLO返回结果构建 网页返回结果
def getContextResult(stat, imgcv, detects, fileSaveDrawBox, fileImageWebPath, isImg =False, fileName=''):
    try:
        if isImg == True:## 是否把图片进行base64编码
            import base64
            with open(fileSaveDrawBox, 'rb') as f:
                data = f.read()
            imgstr = base64.b64encode(data).decode('utf-8')
        else:
            imgstr = []
    except:
        print('Helper(detectResult) 出现异常。。。。。。。。')
        data = getDefaultContext()
    else:
        data = {
            'statusText': '图像检测成功！',
            'statusCode': '200',
            'stat': {'health': stat[0], 'oneleaf': stat[1], 'partial': stat[2], 'seeds': stat[3]},
            'boxes': detects.tolist(),
            'img': imgstr,
            'fileImageWebPath': fileImageWebPath,
            'fileName' : fileName
        }
    return data
## 文件没有找到
def getNoFileDetectResult(fileImageWebPath, fileName=''):
    return {
        'statusText': '图片文件没找到！',
        'statusCode': '505',
        'stat': {'health': 0, 'oneleaf': 0, 'partial': 0, 'seeds': 0},
        'boxes': [],
        'img': [],
        'fileImageWebPath': fileImageWebPath,
        'fileName': fileName
    }

## 设置返回数据，根据实际检测图片数量与  实际图片上传数量 2023-12-23
def getContextResults2(data, nDetects, nUploads):
    if nDetects == nUploads and nUploads > 0:
        statusText = '图像检测成功！'
        statusCode = '200'
    elif nDetects > 0 and nUploads > 0:
        statusText = '部分图像检测成功！'
        statusCode = '202'
    else:
        statusText = '全部图像都检测不成功！'
        statusCode = '404'

    result = {
            'statusText': statusText,
            'statusCode': statusCode,
            'data': data
        }
    return result

##
def round_floats(o):
    if isinstance(o, float): return round(o, 1)
    if isinstance(o, dict): return {k: round_floats(v) for k, v in o.items()}
    if isinstance(o, (list, tuple)): return [round_floats(x) for x in o]
    return o

## 调用YOLO进行图片检测
def detectImage(image_path, isImg, szImage = (0, 0)):##isImg 2022-12-12增加
    import sys
    sys.path.append(getYoloPath())##引入YOLO5库目录
    import test_img_call as tt

    image_path = image_path.replace('\\', '/')
    detect_result_path = getDetectPath()

    isSaveFiles = True
    isSaveFiles = False##不保存中间文件数据，提高网页相应速度

    isSaveResizeImage = True
    isSaveResizeImage = False ##不保存发生缩放与crop的图片，解决前端再次检测重复图片的问题

    baseWebPath = os.getcwd().replace('\\', '/')##保存工程路径
    print('-----------szImage:', szImage)
    try:
        stat, imgcv, detects, fileSaveDrawBox = tt.test_from_web(image_path,
                                                                 detect_result_path,
                                                                 isSaveFiles = isSaveFiles,
                                                                 isSaveImg = isImg,
                                                                 shrink_image=True,
                                                                 from_web = True,
                                                                 szImage = szImage,
                                                                 isSaveResizeImage = isSaveResizeImage)##函数内部会修改工作路径
    except Exception as e:
        print(e, type(e))
    finally:
        os.chdir(baseWebPath)#回复原来的工程路径，test_from_web会删掉
    # print(baseWebPath)
    # print('-----------after:', stat)
    # print('-----------fileSaveDrawBox:', fileSaveDrawBox)

    fileImageWebPath = fileSaveDrawBox.replace(baseWebPath, '')
    print('detectImage:', fileImageWebPath)
    # print('detectImage:', baseWebPath)

    # context = getContextResult(stat, imgcv, detects, fileSaveDrawBox, fileImageWebPath)
    # return context
    return (stat, imgcv, detects, fileSaveDrawBox, fileImageWebPath)
#


##获得YOLO5的库目录
def getYoloPath():
    if os.path.exists('F:/') == True:
        return r'F:\python\yolov5s'     # os.getcwd()  基准目录  notebook
    else:
        return r'D:\zxd\tf2.2\yolov5'   # workstation

def getDetectPath():
    if os.path.exists('F:/') == True:
        return r'F:\python\tobacoo\tmp\web_test_img\detects'     # 中间结果存储路径 notebook
    else:
        return r'D:\zxd\tf2.2\tobacco_web\tmp\web_test_img\detects'   # workstation


